<?php 
/*
 * 类reportManage实现对体检报告的抓取、解析和入库操作
 * 
 * meinianCraw()  美年体检报告的抓取
 * meinianParase()  美年体检报告解析
 * 
 * cimingCraw()   慈铭体检报告抓取
 * cimingParase() 慈铭体检报告解析
 * 
 * aikangCraw()   爱康体检报告抓取
 * aikangParaseSingle()  爱康个人体检报告解析
 * aikangParaseTuan()   爱康团体报告解析
 * 
 * reportInsertDb() 体检报告入库
 */
class reportManage{
		/* 
		 * 美年体检报告抓取
		 */
	
	function json_encode_ex($value)
	{
		if (version_compare(PHP_VERSION,'5.4.0','<'))
		{
			$str = json_encode($value);
			$str = preg_replace_callback(
										"#\\\u([0-9a-f]{4})#i",
										function($matchs)
										{
											 return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
										},
										 $str
										);
			return $str;
		}
		else
		{
			return json_encode($value, JSON_UNESCAPED_UNICODE);
		}
	}
		 
	public function meinianCraw($username,$password){
		
		if (!empty($username) || !empty($username)){
	    $hosturl = "http://meinian.cn";
	//    $loginpagecontent = './report/' . $username . '.html';
	      $loginpagecontent = './filesReport/meinian/' . $username . '.html';
	    $curl_h = curl_init();
	
	    curl_setopt($curl_h, CURLOPT_URL, $hosturl . "/Research.aspx");
	
	    curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);
	
	    curl_setopt($curl_h, CURLOPT_TIMEOUT, 10);
	
	    $output = curl_exec($curl_h);
	
	    $matches = array();
	    $reg_viewstat = "/__VIEWSTATE\" value=\"\/[0-9+A-Za-z]*/i";
	    preg_match($reg_viewstat, $output, $matches);
	    $pos = strripos($matches[0], "\"");
	    $param_viewstate = substr($matches[0], $pos + 1);
	
	//$reg_style = "/ctl00_ContentPlaceHolder1_uStyle(.)*?style/i";
	    $reg_style = "/option [a-z 0-9\"=]*?>个人用户<\/option>/";
	    preg_match($reg_style, $output, $matches);
	    $pos = strripos($matches[0], "\"");
	    $param_style = substr($matches[0], $pos - 1, 1);
	
	    $reg_eventvalidation = "/__EVENTVALIDATION\" value=\"\/[0-9+A-Za-z]*/i";
	    preg_match($reg_eventvalidation, $output, $matches);
	    $pos = strripos($matches[0], "\"");
	    $param_eventvalidation = substr($matches[0], $pos + 1);
	
	
	    $param_viewstate = urlencode($param_viewstate);
	    $param_viewstate = "__VIEWSTATE=" . $param_viewstate . "&";
	    $param_uCard = $username;
	    $param_uPass = $password;
	    $param_button1 = "确定";
	
	    $login_page_url = "http://meinian.cn/Research.aspx?";
	    $login_page_url .= "__EVENTTARGET=&";
	    $login_page_url .= "__EVENTARGUMENT=&";
	    $login_page_url .= $param_viewstate;
	    $login_page_url .= urlencode("ctl00\$ContentPlaceHolder1\$uStyle") . "=$param_style&";
	    $login_page_url .= urlencode("ctl00\$ContentPlaceHolder1\$uCard") . "=$username&";
	    $login_page_url .= urlencode("ctl00\$ContentPlaceHolder1\$uPass") . "=$password&";
	    $login_page_url .= urlencode("ctl00\$ContentPlaceHolder1\$button1") . "=" . urlencode($param_button1) . "&";
	    $login_page_url .= "__EVENTVALIDATION=" . urlencode($param_eventvalidation);
	
	//获 取login之后的页面,获取set-cookie数值
	
	    curl_setopt($curl_h, CURLOPT_URL, $login_page_url);
	    curl_setopt($curl_h, CURLOPT_HEADER, 1);
	
	    $first_page_contents = curl_exec($curl_h);
	    
	    $reg_cookie = "/Set-cookie.*?;/i";
	    preg_match($reg_cookie, $first_page_contents, $matches);
	    if(empty($matches)){
	    	return false;
	    }
	  //  var_dump($matches);exit();
	    $cookie_str = $matches[0];
	    $pos = stripos($cookie_str, "=");
	//获取cookie
	    $cookie = substr($cookie_str, $pos + 1, -1);
	
	    if ($cookie)
	    {
	        $secondpage_path = "/ReportAD.aspx?";
	        $secondepage_url = $hosturl . $secondpage_path . "cid=" . $username;
	
	        curl_setopt($curl_h, CURLOPT_URL, $secondepage_url);
	        curl_setopt($curl_h, CURLOPT_COOKIE, "ASP.NET_SessionId=" . $cookie);
	        curl_setopt($curl_h, CURLOPT_HEADER, 0);
	
	        /*
	         * 获得第二个选择页面，获取数据，进入体检报告列表页
	         */
	//$secondpage_contents = curl_exec($curl_h);
	//
	//$reg_viewstat = "/__VIEWSTATE\" value=\"\/[+0-9A-Za-z=]*/i";
	//preg_match($reg_viewstat, $secondpage_contents, $matches);
	//$pos = strripos($matches[0], "\"");
	//$param_viewstate = substr($matches[0], $pos + 1);
	//
	//$reg_eventvalidation = "/__EVENTVALIDATION\" value=\"\/[0-9+A-Za-z=]*/i";
	//preg_match($reg_eventvalidation, $secondpage_contents, $matches);
	//$pos = strripos($matches[0], "\"");
	//$param_eventvalidation = substr($matches[0], $pos + 1);
	//
	//$post_date = "__VIEWSTATE=" . urlencode($param_viewstate) .
	//    "&Button2=" . urlencode("继续查询报告") .
	//    "&__EVENTVALIDATION=" . urlencode($param_eventvalidation);
	//errors  i don't know why
	//$head = array();
	//$head[] = "POST /ReportAD.aspx?cid=12428175 HTTP/1.1";
	//$head[] = "Host: meinian.cn";
	//$head[] = "Connection: keep-alive";
	//$head[] = "Content-Length: ".strlen($post_date);
	//$head[] = "Cache-Control: max-age=0";
	//$head[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
	//$head[] = "Origin: http://meinian.cn";
	//$head[] = "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36";
	//$head[] = "Content-Type: application/x-www-form-urlencoded";
	//$head[] = "DNT: 1";
	//$head[] = "Referer: http://meinian.cn/ReportAD.aspx?cid=12428175";
	//$head[] = "Accept-Encoding: gzip,deflate,sdch";
	//$head[] = "Accept-Language: zh-CN,zh;q=0.8,de;q=0.6,en;q=0.4,ja;q=0.2,zh-TW;q=0.2";
	//$head[] = "Cookie: ASP.NET_SessionId=".$cookie;
	//curl_setopt($curl_h, CURLOPT_HEADER, $head);
	//curl_setopt($curl_h, CURLOPT_POST, 1);
	//curl_setopt($curl_h, CURLOPT_POSTFIELDS, $post_date);
	//
	//echo $thrid_page = curl_exec($curl_h);
	//$thirdpage_path = "/ResearchResult.aspx?";
	//$thirdpage_url = $hosturl.$thirdpage_path."cid=".$username;
	//
	        $head_tow = array();
	        $head_tow[] = "GET /ResearchResult.aspx?cid=12428175 HTTP/1.1";
	        $head_tow[] = "Host: meinian.cn";
	        $head_tow[] = "Connection: keep-alive";
	        $head_tow[] = "Cache-Control: max-age=0";
	        $head_tow[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
	        $head_tow[] = "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36";
	        $head_tow[] = "DNT: 1";
	        $head_tow[] = "Referer: http://meinian.cn/ReportAD.aspx?cid=" . $_POST['username'];
	        $head_tow[] = "Accept-Encoding: gzip,deflate,sdch";
	        $head_tow[] = "Accept-Language: zh-CN,zh;q=0.8,de;q=0.6,en;q=0.4,ja;q=0.2,zh-TW;q=0.2";
	        $head_tow[] = "Cookie: ASP.NET_SessionId=" . $cookie;
	
	        $third_path = "/ResearchResult.aspx?";
	        $third_url = $hosturl . $third_path . "cid=" . $username;
	
	        curl_setopt($curl_h, CURLOPT_URL, $third_url);
	        curl_setopt($curl_h, CURLOPT_HEADER, $head_tow);
	//curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, 1);
	
	        $thidpage_content = curl_exec($curl_h);
	
	        /*
	         * 获取详细页面之前的一个ShReport页面
	         */
	
	        $reg_search_url = "/ShReport(.)*?\"/";
	
	        preg_match($reg_search_url, $thidpage_content, $matches);
	        if(empty($matches)){
	//        	echo ""
	        	 header("Location:./empty.php");
	        	 exit();
	        }	
	        $tag_href_search = $matches[0];
	        $url_detail = substr($tag_href_search, 0, -1);
	        $url_detail = str_replace(" ", "%20", $url_detail);
	
	        curl_setopt($curl_h, CURLOPT_URL, $hosturl . "/" . $url_detail);
	        curl_setopt($curl_h, CURLOPT_HEADER, 1);
	        curl_setopt($curl_h, CURLOPT_COOKIE, "ASP.NET_SessionId=" . $cookie);
	
	
			$mydetail=str_replace("ShReport", "ResearchDetails", $hosturl . "/" . $url_detail."&flag=1");
	
	        //$url_detailpage_refer_contents = curl_exec($curl_h);
	
	        /*
	         * 利用$url_detailpage中location
	         * 获取详细信息页面
	         */
	        //$reg_search_url = "/ResearchDetail(.)*?\"/";
	
	        //preg_match($reg_search_url, $url_detailpage_refer_contents, $matches);
	        //$tag_href_detail = $matches[0];
	        //$url_detail = substr($tag_href_detail, 0, -1);
	        //$url_detail = str_replace(" ", "%20", $url_detail);
	        //$url_detail = str_replace("&amp;", "&", $url_detail);
	
	        curl_setopt($curl_h, CURLOPT_URL,$mydetail);
	        curl_setopt($curl_h, CURLOPT_HEADER, 0);
	        curl_setopt($curl_h, CURLOPT_COOKIE, "ASP.NET_SessionId=" . $cookie);
	
	        $detailpage_contents = curl_exec($curl_h);
	
	        $detailpage_contents = str_replace("Styles/.css", "Styles/style.css", $detailpage_contents);
	        $detailpage_contents = str_replace("text-align: right;", "display:none", $detailpage_contents);
	        $detailpage_contents = str_replace("no-cache", "text/html;charset=utf-8", $detailpage_contents);
	        $detailpage_contents = str_replace("<head>", "<head><meta http-equiv=Content-Type content='text/html;charset=utf-8'>", $detailpage_contents);
	        $detailpage_contents = str_replace("</head>", "<meta content='width=device-width,user-scalable=no' name='viewport'></head>", $detailpage_contents);
	        $search = array("'<script[^>]*?>.*?</script>'si", // 去掉 javascript 
	            "'<style[^>]*?>.*?</style>'si", // 去掉 css 
	            ); // 作为 PHP 代码运行 
	
	        $replace = array("");
	//$document为需要处理字符串，如果来源为文件可以$document = file_get_contents('http://www.sina.com.cn'); 
	        $detailpage_contents = preg_replace($search, $replace, $detailpage_contents);
	          
	        //echo strpos($detailpage_contents,"</head>");exit();
	        //echo strrpos($detailpage_contents,"</head>");exit();
	        //echo ("<meta name=\"robots\" content=\"noarchive\" >");exit();
	        //$detailpage_contents = str_replace("", "noarchive content='width=device-width,user-scalable=yes' name='viewport'>", $detailpage_contents);
	        $fh = fopen($loginpagecontent, "w+");
	
	        fwrite($fh, $detailpage_contents);
	        fclose($fh);
	        
//	        $username="85140387418560443";   //调试用
//	        $username="601405332960393801";
	        $file="./filesReport/meinian/" . $username . ".html";
	        return $file;
	//        header("Location:./filesReport/meinian/" . $username . ".html");
	       // header("Location:./parser.php?uid=".$username);
	     
	    }
	    else
	    { 
	    	return false;
//	        header("Location:./error.php?id=" . $_POST['id']);
	    }
	}
	else
	{
	 	return false;   
//	    header("Location:./error.php?id=" . $_POST['id']);
	}
			
		}
	
	
	/*
	 * 美年体检报告解析
	 * 把html体检报告解析成指定格式的数组
	 * @param $filename 体检报告名称
	 * return array()
	 */
	public function meinianParse($filename){
	
	header("Content-type: text/html; charset=utf-8");
	
	//$filename = "./filesReport/meinian/85140387418560443.html";
	//$filename = "./filesReport/meinian/601405332660393868.html";
	//$filename="601405326760393827.html";
//	$filename="./filesReport/meinian/15199302.html";
	//测试
//	$filename="./test/85140387418560443.html";		//胸部DR正位片
	//$filename="./test/96140229439638359.html";		//胸部DR正位检查（图文
	$content = file_get_contents($filename);
	//$content=iconv('gbk', 'utf-8', $content);
	
	$data=array();  //所有内容
	
	/*
	 * 获取基本信息
	 */
	$pattern_basic="/个人基本信息(.*)<td height=\"1\" bgcolor=\"#d1d1d1\">/isU";
	preg_match($pattern_basic, $content, $matches);
//	var_dump($matches);exit();
	$result_basic=$matches[0];
	
	//获取基本信息中小项目名称
	//$pattern_basic_item_name="/<td align=\"left\" class=\"brown02_12\">(.*)<\/td>/isU";
	$pattern_basic_item_name="/(<td align=\"left\" class=\"brown02_12\">|<td height=\"30\" align=\"left\" class=\"brown02_12\">)(.*)<\/td>/isU";

	preg_match_all($pattern_basic_item_name, $result_basic, $matches);
	$array_basic_item_name=array();
	foreach($matches[0] as $key=>$val){
		array_push($array_basic_item_name, trim(strip_tags($val)));
	}
	//获取基本信息中小项目的值
	$pattern_basic_item_value="/<td align=\"left\" class=\"black_12\">(.*)<\/td>/isU";
	preg_match_all($pattern_basic_item_value, $result_basic, $matches);
	$array_basic_item_value=array();
	foreach ($matches[0] as $key=>$val){
		array_push($array_basic_item_value, trim(strip_tags($val)));
	}
//	var_dump($array_basic_item_name);
//	var_dump($array_basic_item_value);
//	exit();
	
	//把key和value进行组合
	$basic_itemSet=array();
	$ret_basic=array_combine($array_basic_item_name, $array_basic_item_value);
	foreach($ret_basic as $key=>$val){
		array_push($basic_itemSet, array("itemName"=>$key,"itemValue"=>$val));
	}
//	var_dump($basic_itemSet);exit();
	array_push($data, array("parentName"=>"基本信息","itemSet"=>$basic_itemSet));
//	var_dump($basic_itemSet);exit();
	//整理出用户基本信息，为了入库
		$reportinfo=array('realname'=>'','gender'=>'','examno'=>'','examdate'=>'');
		foreach($basic_itemSet as $key=>$val){
//			var_dump(substr($val['itemName'],0,9));
			if(substr($val["itemName"],0,6)=="姓名"){
				$reportinfo['realname']=$val["itemValue"];
			}
			
			if(substr($val["itemName"],0,6)=="性别"){
					$reportinfo['gender']=$val["itemValue"];
//					var_dump($reportinfo['gender']);exit();
				}
			
			if(substr($val['itemName'],0,9)=="体检号"){
				$reportinfo["examno"]=$val['itemValue'];
			}
			
			if(substr($val['itemName'],0,12)=="体检时间"){
				$reportinfo["examdate"]=$val['itemValue'];
			}
			
		}
//		exit();
//		exit();
//	var_dump($reportinfo);exit();
	//筛选出各个体检大项
//	$patten="/<td class=\"brown02_14\" style=\"color:#ED9C72\">(.*)<td align=\"left\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">/isU";
//	$patten="/<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">(.*)<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">/isU";
	$patten="/<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">(.*)<td align=\"left\">/isU"; 
	
	preg_match_all($patten,$content,$matches);
	$result_large_project=$matches[0];
//	var_dump($result_large_project);exit();
	/*
	 * 处理各个体检大项目的内容
	 */
	foreach($result_large_project as $key=>$val){
		
		//筛选出每一体检项目的parentName
		//匹配小项目套餐
		$pattern_parentName="/(<td class=\"brown02_14\" style=\"color: #ED9C72\">(.*)<\/a><\/td>)|(<span id=\"Repeater1_ct(.*)<\/span><\/td>)/isU";
		preg_match_all($pattern_parentName, $val, $matches);
//		var_dump($pattern_parentName);continue;
		if(isset($matches[0][0])){
			$parentName=strip_tags($matches[0][0]);
		
			//筛选出每一小项html
			$pattern_tr="/<tr>(.*)<\/tr>/isU";
			preg_match_all($pattern_tr, $val, $matches);
			//筛选出每一个体检小项目中的指标的值
			$itemSet=array();
			foreach($matches[0] as $key=>$val){
				$patten_td = "/<td align(.*)<\/td>/isU";
				preg_match_all($patten_td, $val, $matches);
				//去掉每个小项值中的html标签
				$result_td=array();
				foreach($matches[0] as $key=>$val){
					array_push($result_td, strip_tags($val));
				}
				
				//向数组赋予指定格式的key
				if(count($result_td)==4){
					$result_combine = array_combine(array("itemName","itemValue","unit","normal"), $result_td);
					array_push($itemSet, $result_combine);
				}
			}
			$result=array("parentName"=>$parentName,"itemSet"=>$itemSet);
			array_push($data, $result);
		}
		unset($pattern_parentName);
	}
//	var_dump($data);
//	exit();
	//筛选出“总检”内容
	//$patter_summary="/\* 您好，欢迎您来到美年大(.*)<\/td>/isU";
	$patter_summary="/\*(.*)<\/td>/isU";
	preg_match($patter_summary, $content, $matches);
	array_push($data, 
		array("parentName"=>'总检',
				"itemSet"=>array(
					array("itemName"=>"总检","itemValue"=>$matches[1])
		),
	));
	//var_dump($data);exit();
	//$json = json_encode($data,JSON_UNESCAPED_UNICODE);   //输出json格式
	$json = json_encode_ex($data);
	$json = str_replace('\r\n\r\n', '', $json);
// 	$json = str_replace('\r', '', $json);
// 	$json = str_replace('\n', '', $json);
// 	$json = str_replace('\t', '', $json);
 	$json = str_replace('\&nbsp;', '', $json);
//	echo "你好";exit();
 	
 	 $qian=array(" ","　","\t","\n","\r","&nbsp;");
 	 $hou=array("","","","","","");
    $json = str_replace($qian,$hou,$json);
 	$data = json_decode($json,true);
 	return array("data"=>$data,"reportinfo"=>$reportinfo);
	}
	
	/*
	 * 筛选内容
	 * @param $examid   体检号
	 * 		$password   密码
	 * return $reportid 体检报告reportid
	 * 			false  如果体检报告不存在，返回false
	 */
	public function checkReportExist($examid,$password){
		$con = mysql_connect('114.215.136.195', 'root', 'Abcde12345');
//		$con = mysql_connect('localhost', 'root', 'ins');
		mysql_select_db('report',$con);
		if (!$con)
		{
		  die('Could not connect: ' . mysql_error());
		}
		$sql=<<<EOF
			SELECT `reportid` from 	`reportinfo` where `examid` ="$examid" and `password`="$password" order by `reportid` desc
EOF;
		//var_dump($sql);exit();
		$result = mysql_query($sql);
		$row = mysql_fetch_row($result);
//		var_dump($row);exit();
		if(empty($row)){
			return false;
		}else{
			return $row[0];
		}
	  	
	}
	
	/*
	 * 入库操作
	 * @param $arrayItemResult  体检号
	 * return $reportid
	 */
	public function reportInsertDb($reportinfo,$arrayItemResult){
		//var_dump($arrayItemResult);exit();
	 
		 //入库操作
        $mysqli = new mysqli('114.215.136.195', 'root', 'Abcde12345', 'report');
//       $mysqli = new mysqli('127.0.0.1', 'root', 'ins', 'report');

        if ( mysqli_connect_errno ()) {
//            printf ( "Connect failed: %s\n" ,  mysqli_connect_error ());
            return false;
        }
        $mysqli->query("set names utf8");

        $realname = $reportinfo["realname"];
        $examdate = $reportinfo["examdate"];
        $examid =   $reportinfo["examid"];
//        var_dump($examid);exit();
        $password =  $reportinfo["password"];

        $genderNo = 0;
        if ($reportinfo["gender"] == '男') {
            $genderNo = 1;
        }else if ($reportinfo["gender"] == '女') {
            $genderNo = 2;
        }
		$infosql=<<<EOF
			insert into `report`.`reportinfo` (`username`,`gender`,`examtime`,`examid`,`password`) values("$realname","$genderNo","$examdate","$examid","$password")
EOF;
        $mysqli -> query ( $infosql );
        $reportid = $mysqli->insert_id;
		
        if(isset($arrayItemResult['data'])){
        	$arrayItemResult=$arrayItemResult['data'];
        }
        
        foreach ($arrayItemResult as $parent)
        {
            if ($parent["parentName"] == "basic") {
                continue;
            }

            $parentName = $parent["parentName"];
            $parentsql = "insert into report.programinfo(reportid, programname) values($reportid, '"."$parentName')";

            $mysqli -> query ( $parentsql );
            $programid = $mysqli->insert_id;


            $itemSet = $parent["itemSet"];
            foreach ($itemSet as $item) {
                $itemname = trim($item["itemName"]);
                $result = trim($item["itemValue"]);
                //单位
                if(array_key_exists("unit", $item)){
                	$unit = trim($item["unit"]);
                }else{
                	$unit="";
                }
                
                //范围
            	if(array_key_exists("normal", $item)){
                	$normal = trim($item["normal"]);
                }else{
                	$normal="";
                }
//                $normal = $item["normal"];
				//异常
				if(array_key_exists("issue", $item)){
					$issue = ($item['issue']);
				}else{
					$issue="";
				}
//                $issue = $item["issue"];
                $itemsql = "insert into report.iteminfo(reportid,programid,itemname,result,unit,normal,issue) values($reportid, $programid, '$itemname', '$result', '$unit', '$normal','$issue')";
                $mysqli -> query ( $itemsql );
            }
        }
        return $reportid;
	}
	
	/*
	 * 慈铭体检报告抓取
	 * @param $username  体检号
	 * 		  $password 密码
	 * return 体检报告路径
	 */
	public function cimingCraw($username,$password){
//		$username="%2F000101014061871575";
//		 $file="./filesReport/ciming/" . $username . ".html";
//	     return $file;

       
        $url = "http://book.ciming.com/command/dispatcher/org.online.web.cmd.report.UcReportCmd/selectCode?ajax=yes";
        $post = 'queryCode1='.$username;
        $post.= '&passWord1='.md5($password);
        $post.= '&paperCode=2013092520294500000000057';
        $ch = curl_init();
        $headers[] = "Content-type: application/x-www-form-urlencoded"; 
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $ret=curl_exec($ch);
        curl_close($ch);
        /* 写入文件 */
        $jsondecode = json_decode($ret);
//        var_dump($jsondecode);exit();
        $property = property_exists($jsondecode,"rptAdd");
//        var_dump($ret);exit();
        if(!$property){
        	return false;
        }
     
        $rptAdd = $jsondecode->rptAdd;

		$url = "http://book.ciming.com/previewReport.htm?filename={$rptAdd}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($ch);
       
        $ret = str_replace("charset=GB2312","charset=utf8" , $ret);
        curl_close($ch);
        /* 写入文件 */
        $fh = fopen("./filesReport/ciming/".$username.".html", 'w') ;
//        var_dump($fh);exit();
        $ret = fwrite($fh, $ret);
        $filename = "./filesReport/ciming/".$username.".html";
        return $filename;
        fclose($fh);
	}
	
	/*
	 * 慈铭体检报告解析
	 * @param $filename
	 * return  array()
	 */
	public function cimingParase($filename){
		
		//require_once '../standard.php';
		header("Content-type: text/html; charset=utf-8");
	//	$fileReports = "aa.html";
//		$filename ="%2F000101014061871575";
//		 $filename="./filesReport/ciming/" . $filename . ".html";
	//	$fileReports="%2F009900113101919697.html";
	
		
		$content = file_get_contents($filename);
//		$content=iconv('GBK', 'utf-8', $content);
		$data=array();  //所有内容
	
		//个人基本信息
		$patten_basic="/(以下内容由客人本人提供)(.*)<div class=div647>/isU";    
		
		preg_match($patten_basic, $content,$matches);
	//	var_dump($matches);exit();
		$basic_info = $matches[0];
		$pattern="/<td(.*)<\/td>/isU";
		preg_match_all($pattern, $basic_info,$matches);
		
		foreach($matches[0] as $key=>$val){
			if($key%2!=0){
				$basic_info_values[]=trim(strip_tags($val));
			}else{
				$basic_info_keys[]=trim(strip_tags($val));
			}
		}
		
		$basic_itemSet=array();
		$basic_info = array_combine($basic_info_keys, $basic_info_values);
		
		//获取慈铭体检报告个人信息，便于入库，插入“牛逼体检报告”项目中的report.reportinfo表
//		$reportinfo=array();
		$reportinfo=array('realname'=>'','gender'=>'','examno'=>'','examdate'=>'');
		$reportinfo['realname']=$basic_info['姓名'];
		$reportinfo['gender']=$basic_info['性别'];
		if(array_key_exists("体检时间", $basic_info)){
			$reportinfo['examdate']=$basic_info['体检时间'];
		}
		
		
//		var_dump($reportinfo);exit();
		foreach ($basic_info as $key=>$val){
			//我想在这里删掉内容为空的小项，但是删不掉？？？？？？？？？？
			if(empty($val)){
				unset($basic_info[$key]);
			}
			
			array_push($basic_itemSet, array("itemName"=>$key,"itemValue"=>$val));
		}
		
//		var_dump($basic_itemSet);exit();
		
		
		
		
		
//		var_dump($basic_info);exit();
		$basic_info = array("parentName"=>"basic","itemSet"=>$basic_itemSet);
		
		array_push($data, $basic_info);
	
	
		
		//匹配大项，筛选出每一大项的内容
		$pattern = "/<strong>&nbsp;&nbsp;<u>(.*)<\/div>/isU";
		preg_match_all($pattern, $content, $matches);
	
		
		//循环每一大项
		foreach($matches[0] as $key=>$val){
			//var_dump($val);continue;
			//匹配体检项目大项名称
			$patten_parentName="/<strong>&nbsp;&nbsp;<u>(.*)<\/u><\/strong>/isU";
			preg_match_all($patten_parentName, $val, $matches_parentName);
			$parentName=trim($matches_parentName[1][0]);
	
			//筛选出每一小项的所有html内容
			$pattern_tr="/<td valign=top>(.*)<\/tr>/isU";
			//$patten_tr="/<tr(.*)<\/tr>/isU";
			preg_match_all($pattern_tr, $val, $matches);
			//var_dump($matches[0]);continue;
			//array_shift($matches[0]);
			//var_dump($matches[0]);continue;
			
			//定义小项key的名称
			$keys=array("itemName","itemValue","unit","normal");
			$keys_short=array("itemName","itemValue");
			$keys_shor_middle=array("itemName","itemValue","unit");
			
			//获取每一条小项的指标数值
			$itemSet=array();
			foreach($matches[0] as $key=>$val){
	//			var_dump($val);continue;
				
				//提取“项目”，“单位”，“结果”，“参考范围”的值
				$patten ="/<td(.*)<\/td>/isU";
				//var_dump($val);continue;
				preg_match_all($patten, $val, $matches_item);
	
				$array_item=array();
				foreach ($matches_item as $key=>$val){
					$array_inner=array();
					foreach ($val as $k=>$v){
						//去掉空格
						$str = trim(strip_tags($v));
						$new_str = str_replace("&nbsp;", '', $str);
						array_push($array_inner, $new_str);
					}
	//				var_dump($val);continue;
					array_push($array_item, $array_inner);
				}
				unset($array_item[0][2]);
				//var_dump($array_item[0]);continue;
	
				//把每一小项目的key值和value值对应上
				if(count($array_item[0])===4){
					$rets = array_combine($keys, $array_item[0]);
				}elseif(count($array_item[0])===2){
					$rets=array_combine($keys_short, $array_item[0]);
				}elseif(count($array_item[0])===3){
					$rets=array_combine($keys_shor_middle, $array_item[0]);
				}
				
				array_push($itemSet, $rets);
			}
	//		exit();
			
			//各大项名称和大项指标合并
			$item = array("parentName"=>$parentName,"itemSet"=>$itemSet);
			array_push($data, $item);
		}
		
			//匹配“总汇”内容
			$patten_confluence="/<center>(.*)<\/div>/isU";
			preg_match($patten_confluence, $content,$matches);
		
			$confluence = array("parentName"=>"总汇",
									"itemSet"=>array( array("itemName"=>"总汇","itemValue"=>trim(strip_tags($matches[1]))))
								);
			array_push($data, $confluence);
//			var_dump($data);exit();
			
			return array("data"=>$data,"reportinfo"=>$reportinfo);

//		$json = json_encode($data,JSON_UNESCAPED_UNICODE);
//	 	$json = str_replace('\r\n\r\n', '', $json);
//	 	$json = str_replace('\r', '', $json);
//	 	$json = str_replace('\n', '', $json);
	 	//echo $json;
	 	
	 	/*
	 	 * 体检报告格式统一化
	 	 */
//	 	$arrayItemResult=json_decode($json,true);
//	 	
//	 	$p=new reportStandard();
//		$p->standard($arrayItemResult, "ciming");
 	
	
		
	}
	
	/*
	 * 爱康体检报告抓取
	 * @param $username 用户名
	 * 		$password 密码
	 * return 保存到本地的文件地址
	 */
 public  function aikangCraw($username,$password)
    {
//    	var_dump($username);exit();
        $url = "http://tech.health.ikang.com/app/pub/memberapp/loginCheck?cardnumber=".$username."&password=".$password;
//		var_dump($url);exit();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($ch);
        curl_close($ch);
        /* 写入文件 */
        $fh = fopen("./filesReport/temp/validation.html", 'w') ;
        fwrite($fh, $ret);
        fclose($fh);
        $htmlStr = file_get_contents("./filesReport/temp/validation.html");
//		var_dump($htmlStr);exit();
		if($htmlStr=="-1" || $htmlStr=="-2"){
			return false;
		}
        list($memberid, $b) = @split('[|]', $htmlStr);
        $key = $memberid.$b;
//        echo $key;
//		exit();
		
		$post = 'key='.$key;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://tech.health.ikang.com/app/pub/md5");
        ///curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $result=curl_exec($ch);
        curl_close($ch);

        /* 写入文件 */
        $fh = fopen("./filesReport/temp/list.html", 'w') ;
        fwrite($fh, $result);
        fclose($fh); 
        $Authorization = file_get_contents("./filesReport/temp/list.html");
		
			$ch = curl_init();
            $headers[] = "Authorization:".$Authorization; 
            $headers[] = "MemberId:".$memberid; 
//            var_dump($memberid);exit();
            curl_setopt($ch, CURLOPT_URL, "http://tech.health.ikang.com/app/report/findReportByMemberId?memberid=".$memberid);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $ret = curl_exec($ch);
            curl_close($ch);
            //echo $ret;
            $jsondecode = json_decode($ret);
//            var_dump($jsondecode);exit();
            foreach ($jsondecode as $va){
                $checknumbers = $va->checknumbers;
            }
			
			$ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://tech.health.ikang.com/app/report/downLoadReport?cardnumber=".$username."&checknumber=".$checknumbers);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $ret = curl_exec($ch);
            curl_close($ch);
            //var_dump($ret);
            $fh = fopen("/home/pdf/".$username.".pdf", 'w') ;
//            var_dump($fh);exit();
//			var_dump($ret);exit();
            fwrite($fh, base64_decode($ret));
            fclose($fh);
            return $username;
    }
    
    /*
     * 爱康个人体检报告解析
     * @filename 爱康体检报告
     * return array()
     * 			false 团体报告返回false
     */
    public function aikangParseDan($filename){
    	  $a = file($filename);
//    	  var_dump($a);exit();
        $lines = array();
        foreach ($a as $line => $content) {
            //echo 'line '.($line + 1).':'.$content;
            $content = rtrim($content);
            if (strpos($content, "版权所有") === false && strpos($content, "健康检查报告") === false) {
                $lines[] = $content;
            }
        }

        // 1. get basic reportinfo
        $reportinfo=array('realname'=>'','gender'=>'','examno'=>'','examdate'=>'');
//        var_dump($lines);exit();
        foreach ($lines as $oneLine) {
            if (strpos($oneLine, "欢迎您的光临") !== false) {
                preg_match("/\[(.*)]/", $oneLine, $matches);
                if(empty($matches)){return false;}
//                var_dump($matches);continue;
                $reportinfo["address"] = $matches[1];
            } elseif (strpos($oneLine, "用户姓名") !== false) {
                $item = explode("：", $oneLine);
                $reportinfo["realname"] = $item[1];
            } elseif (strpos($oneLine, "性别") !== false) {
                $item = explode("：", $oneLine);
                $reportinfo["gender"] = $item[1];
            } elseif (strpos($oneLine, "体检日期") !== false) {
                $item = explode("：", $oneLine);
                $reportinfo["examdate"] = $item[1];
            }
        }
//          exit();
        // var_dump($lines);exit();
        if(!isset($reportinfo["realname"])||!isset($reportinfo["gender"])){
            return array("error"=>'非法体检报告');
        }
//       var_dump($reportinfo);	//获取到用户基本信息
    



        $itemsArray = array();

        $scopeMark = "~";
        $otherMark = " ";
        $lastScope = 0;
        $isScope = 0;


        $nowProgramName = "";
        $programArray = array();

        // 2. get iteminfos
        foreach ($lines as $oneLine) {
            if (strpos($oneLine, "专家指导") !== false) {
                $isScope = 3;
                $prefix = "";
            } elseif (strpos($oneLine, "检查项目") !== false) {
                //        echo "\n";
                //** echo $lastLine . "\n";    ///    大项目名称
                $nowProgramName = $lastLine;

                if (strpos($oneLine, "参考") !== false) {
                    $isScope = 1;
                } else {
                    $isScope = 2;
                }
                $prefix = "";
                $lastScope = 0;
            } else {
                if ($isScope != 3 && strpos($oneLine, "初步意见") !== FALSE) {
                    $prefix = "";
                    continue;
                }

                if ($isScope != 3 && strpos($oneLine, "视力") !== FALSE && strpos($oneLine, " ") === FALSE){
                    $prefix = "";
                    continue;
                }

                if ($isScope != 3 && $oneLine == "") {
                    $prefix = "";
                    $lastScope = 0;
                    continue;
                }

                if ($isScope != 3 && strpos($oneLine, "检查项目") === false && strpos($oneLine, "检查") !== false) {
                    $prefix = "";
                    $lastLine = $oneLine;
                    continue;
                }

                //***      echo $prefix . " -------------88888\n";
                if ($isScope == 1) {
                    $prefix = $prefix . $oneLine;
                    if (strpos($oneLine, $scopeMark) !== false) {

                        $itemsArray[] = $prefix;
                        $programArray[] = $nowProgramName;
                        $prefix = "";
                    }
                } elseif ($isScope == 2) {

                    $size = count($itemsArray);

                    if (strpos($oneLine, $otherMark) !== false) {
                        //                echo $prefix . "\n";
                        $itemsArray[] = $oneLine;
                        $programArray[] = $nowProgramName;
                        $prefix = "";
                    }else {
                        if ($lastScope == $isScope) {
                            $itemsArray[$size - 1] = $itemsArray[$size - 1] . $oneLine;
                        }
                    }
                } elseif ($isScope == 3) {
                    $prefix = $prefix . $oneLine . "\n";
                }
            }

            $lastLine = $oneLine;
            $lastScope = $isScope;
        }

        //***  echo "---------------------------------" . "\n" . $prefix;   //体检报告最后的总结

        /*
         * 把小项中的内容整理成固定格式，key分别为itemName,itemValue,issue,normal,unit,
         * 思路：
         * 1.用空格分割$itemsArray
         * 2.分割后的$itemsArray包括"~",则分配到normal（范围）中
         * 3.其它的按照：itemName,itemValue,issue,normal,unit进行分配
         *
         */
        //  var_dump($itemsArray);  //转化前小项所有内容
        $itemsArrayResult = array();
        //var_dump($itemsArray);exit();
        //$str = explode(" ", $itemsArray[84]);
        //var_dump($str);exit();
        foreach ($itemsArray as $key=>$val){
            //	var_dump($val);continue;
            //	$val = explode(" ", $val);
            $val = preg_split('/[\n\r\t\s]+/isU', $val);
            //若包含缩写，则把缩写合并到itemName中
            /***
            if(ctype_alpha(substr($val[1],0,1))){
            $val[0]=$val[0].$val[1];
            unset($val[1]);
            }
             ***/
            if(preg_match("/[A-Z]/isU", $val[1])){
                $val[0]=$val[0]." ".$val[1];
                //		var_dump($val[0]);continue;
                unset($val[1]);
            }

            //重新定义索引
            $val=array_values($val);

            //把小项的value和指定的key值合并
            $keys_two = array("itemName","itemValue");
            $keys_three = array("itemName","itemValue","normal");



            $keys_four = array("itemName","itemValue","normal","unit");
            $keys_five = array("itemName","itemValue","issue","normal","unit");
            //	var_dump($val);continue;
            if(count($val)===2){
                //		var_dump($val);continue;
                $val_combine=array_combine($keys_two, $val);
                $str=explode(" ", trim($val[0]));
                //		var_dump($str);continue;
                if(count($str)==2){
                    //			var_dump($str);continue;
                    $val = array_merge($str,array($val[1]));
                    $val_combine=array_combine($keys_three, $val);
                    //			var_dump($val_combine);exit();
                }

            }elseif(count($val)===3){
                //		var_dump($val);continue;
                $val_combine=array_combine($keys_three, $val);
            }elseif(count($val)===4){
                $val_combine=array_combine($keys_four, $val);
            }elseif(count($val)===5){
                //		var_dump($val);continue;
                $val_combine=array_combine($keys_five, $val);
            }else{
                //		var_dump($val);exit();
                $val_combine=array_combine($keys_two,explode(" ", $val[0]));
            }
            //	exit();
            array_push($itemsArrayResult, $val_combine);
        }
        //var_dump($itemsArrayResult);
        //exit();

        //var_dump($itemsArrayResult); exit(); //各个itemSet中的内容，即每一小项指标
        $uniqueProgramArray=array_unique($programArray);  //$uniqueProgramArray为删除大项中的重复项目

        //var_dump($programArray);//大项所有名称
        /*
         * 循环value值唯一的大项数组，组成含有parentName和itemSet的数组
         */
        $arrayParentName=array();  //删除重复项，含有parentName和itemSet的数组
        foreach($uniqueProgramArray as $key=>$val){
            $item=array("parentName"=>$val,"itemSet"=>array());
            array_push($arrayParentName, $item);
        }

        /**生成最终结果**/
        $arrayItemResult=array();  //保存最终结果的最外层数组
        array_push($arrayItemResult, array("parentName"=>"basic","itemSet"=>array($reportinfo)));	//添加用户基本信息

        //向itemSet中插入体检指标
        foreach($arrayParentName as $key=>$val){      //循环含有parentName和itemSet的数组
            foreach ($programArray as $k=>$v){		//循环大项所有名称，共93个
                if($v==$val["parentName"]){
                    array_push($val["itemSet"], $itemsArrayResult[$k]);
                }
            }
            array_push($arrayItemResult, $val);
        }

        array_push($arrayItemResult, array("parentName"=>"总汇","itemSet"=>array(array("itemName"=>"总汇","itemValue"=>$prefix)))); 	//添加总结
    	//echo json_encode($arrayItemResult);exit();
        return array("reportinfo"=>$reportinfo,"arrayItemResult"=>$arrayItemResult);
    }
 
   
}